<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">




  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Jetpack,LiveData,">





  <link rel="alternate" href="/atom.xml" title="Colin's Blog" type="application/atom+xml">






<meta name="description" content="声明： 本文翻译自Medium 文章   LiveData可能会丢失数据。在你说“没关系”之前，请检查所有的情况。  LiveData是谷歌的Android架构中最引人注目的明星组件之一。基本上，它是一个可观察的数据持有者，并在观察者处于活动状态时将数据更改发送给观察者。在Android应用程序中，视图通常附加到生命周期感知组件，如片段或活动。然而，生命周期感知组件可能被杀死、重新创建或分离(">
<meta name="keywords" content="Jetpack,LiveData">
<meta property="og:type" content="article">
<meta property="og:title" content="LiveData may lost Data">
<meta property="og:url" content="http://duanyitao.com/2019/12/30/LiveData-may-lose-Data/index.html">
<meta property="og:site_name" content="Colin&#39;s Blog">
<meta property="og:description" content="声明： 本文翻译自Medium 文章   LiveData可能会丢失数据。在你说“没关系”之前，请检查所有的情况。  LiveData是谷歌的Android架构中最引人注目的明星组件之一。基本上，它是一个可观察的数据持有者，并在观察者处于活动状态时将数据更改发送给观察者。在Android应用程序中，视图通常附加到生命周期感知组件，如片段或活动。然而，生命周期感知组件可能被杀死、重新创建或分离(">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://miro.medium.com/proxy/1*GKpyv8DQ3qJMKvpGWEVIyw.jpeg">
<meta property="og:image" content="https://miro.medium.com/max/1077/1*OobWCz4qZm6XNHk-PxWP0A.png">
<meta property="og:image" content="https://miro.medium.com/max/1078/1*QLCjpBsQ_DezOpQIEbI4PQ.png">
<meta property="og:updated_time" content="2019-12-30T09:27:10.532Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="LiveData may lost Data">
<meta name="twitter:description" content="声明： 本文翻译自Medium 文章   LiveData可能会丢失数据。在你说“没关系”之前，请检查所有的情况。  LiveData是谷歌的Android架构中最引人注目的明星组件之一。基本上，它是一个可观察的数据持有者，并在观察者处于活动状态时将数据更改发送给观察者。在Android应用程序中，视图通常附加到生命周期感知组件，如片段或活动。然而，生命周期感知组件可能被杀死、重新创建或分离(">
<meta name="twitter:image" content="https://miro.medium.com/proxy/1*GKpyv8DQ3qJMKvpGWEVIyw.jpeg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":20,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://duanyitao.com/2019/12/30/LiveData-may-lose-Data/">





  <title>LiveData may lost Data | Colin's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Colin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">时间是没有声音的锉刀。</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-android">
          <a href="/categories/Android/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-android"></i> <br>
            
            Android
          </a>
        </li>
      
        
        <li class="menu-item menu-item-kotlin">
          <a href="/categories/Kotlin/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-code"></i> <br>
            
            Kotlin
          </a>
        </li>
      
        
        <li class="menu-item menu-item-dart">
          <a href="/categories/Dart/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-terminal"></i> <br>
            
            Dart
          </a>
        </li>
      
        
        <li class="menu-item menu-item-flutter">
          <a href="/categories/Flutter/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-road"></i> <br>
            
            Flutter
          </a>
        </li>
      
        
        <li class="menu-item menu-item-ios">
          <a href="/categories/iOS/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-apple"></i> <br>
            
            iOS
          </a>
        </li>
      
        
        <li class="menu-item menu-item-web">
          <a href="/categories/Web/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-html5"></i> <br>
            
            Web
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vim">
          <a href="/categories/Vim/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-code"></i> <br>
            
            Vim
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://duanyitao.com/2019/12/30/LiveData-may-lose-Data/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="段燚涛">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Colin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">LiveData may lost Data</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-30T17:13:13+08:00">
                2019-12-30
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-12-30T17:27:10+08:00">
                2019-12-30
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.2k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <blockquote>
<p>声明： 本文翻译自<a href="https://medium.com/@hanyuliu/livedata-may-lose-data-2fffdac57dc9" target="_blank" rel="noopener">Medium 文章</a></p>
</blockquote>
<blockquote>
<p>LiveData可能会丢失数据。在你说“没关系”之前，请检查所有的情况。</p>
</blockquote>
<p>LiveData是谷歌的Android架构中最引人注目的明星组件之一。基本上，它是一个可观察的数据持有者，并在观察者处于活动状态时将数据更改发送给观察者。在Android应用程序中，视图通常附加到生命周期感知组件，如片段或活动。然而，生命周期感知组件可能被杀死、重新创建或分离(片段)，这使得访问视图变得危险和复杂。为了使视图层操作更加友好，LiveData向它的观察者引入了生命周期感知。每个观察者可以与一个LifecycleOwner相关联，通常是一个片段或活动，并防止在其LifecycleOwner不活动时将数据更改发送给观察者。此行为可以确保在执行不是“必要的”情况下，观察者中的逻辑不会被执行。例如，如果一个片段正在分离，它的视图将很快被销毁。在分离过程中，这个片段视图上的任何视图层操作都是不可见的，也是不必要的。相反，LiveData缓冲最后的数据更改，并在片段重新连接和重新创建视图时通知观察者，这可以将新视图实例“恢复”到最新状态，并防止潜在的NPE或内存泄漏。<br>但是，由于LiveData在主线程上分发数据，并且只缓冲一个挂起的数据更改，所以您的观察者很少会错过或没有接收到数据更改。尽管谷歌的文档从未将LiveData定义为类似于rxjava的流框架，也没有建议使用LiveData，只是在视图和VM之间建立一个薄薄的粘合层，但我们仍然有必要研究所有可能的数据丢失场景，并避免生产中可能出现的意外行为。在下一节中，我们将通过示例讨论三种数据丢失情况。</p>
<h2 id="将数据发送到活动状态之外"><a href="#将数据发送到活动状态之外" class="headerlink" title="将数据发送到活动状态之外"></a>将数据发送到活动状态之外</h2><p>LiveData是一个支持生命周期的组件。因此，只有在其LifecycleOwner处于活动状态时，才能将数据更改交付给观察者。如下图所示，当一个LifecycleOwner切换到“STARTED”或“resume”时，它是活动的。因此，LiveData观察者只能在其LifecycleOwner“启动”或“恢复”时接收数据更改更新。如果数据源将数据发送到活动状态之外的LiveData，则观察者将不会接收发送的数据。</p>
<p><img src="https://miro.medium.com/proxy/1*GKpyv8DQ3qJMKvpGWEVIyw.jpeg" alt="图片"></p>
<p>假设我们有一个活动，它在其生命周期回调中将数据写入MutableLiveData。一个观察者正在观察MutableLiveData并打印出接收到的数据。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ActiveGapActivity</span> <span class="title">extends</span> <span class="title">BaseActivity</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> static MutableLiveData&lt;String&gt; mutableLiveData = new MutableLiveData&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> void onCreate(<span class="meta">@Nullable</span> Bundle savedInstanceState) &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        mutableLiveData.observe(<span class="keyword">this</span>, new Observer&lt;String&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> void onChanged(<span class="meta">@Nullable</span> String string) &#123;</span><br><span class="line">                System.<span class="keyword">out</span>.println(<span class="string">"ActiveGapActivity Observed: "</span> + string);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        mutableLiveData.setValue(<span class="string">"onCreate"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> void onResume() &#123;</span><br><span class="line">        <span class="keyword">super</span>.onResume();</span><br><span class="line">        mutableLiveData.setValue(<span class="string">"onResume"</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> void onPause() &#123;</span><br><span class="line">        <span class="keyword">super</span>.onPause();</span><br><span class="line">        mutableLiveData.setValue(<span class="string">"onPause"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> void onStop() &#123;</span><br><span class="line">        <span class="keyword">super</span>.onStop();</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"ActiveGapActivity onStop called"</span>);</span><br><span class="line">        mutableLiveData.setValue(<span class="string">"onStop"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> void onDestroy() &#123;</span><br><span class="line">        <span class="keyword">super</span>.onDestroy();</span><br><span class="line">        mutableLiveData.setValue(<span class="string">"onDestroy"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果我们旋转app并触发Activity recreation，会打印如下日志:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">ActiveGapActivity Observed: onCreate</span><br><span class="line">ActiveGapActivity Observed: onResume</span><br><span class="line">ActiveGapActivity Observed: onPause</span><br><span class="line">ActiveGapActivity onStop called       <span class="tag">&lt;<span class="name">==</span> <span class="attr">onStop</span>() <span class="attr">is</span> <span class="attr">called</span></span></span><br><span class="line"><span class="tag"><span class="attr">ActiveGapActivity</span> <span class="attr">Observed:</span> <span class="attr">onCreate</span></span></span><br><span class="line"><span class="tag"><span class="attr">ActiveGapActivity</span> <span class="attr">Observed:</span> <span class="attr">onResume</span></span></span><br><span class="line"><span class="tag"><span class="attr">ActiveGapActivity</span> <span class="attr">Observed:</span> <span class="attr">onPause</span></span></span><br><span class="line"><span class="tag"><span class="attr">ActiveGapActivity</span> <span class="attr">onStop</span> <span class="attr">called</span></span></span><br><span class="line"><span class="tag"><span class="attr">ActiveGapActivity</span> <span class="attr">Observed:</span> <span class="attr">onCreate</span></span></span><br><span class="line"><span class="tag"><span class="attr">ActiveGapActivity</span> <span class="attr">Observed:</span> <span class="attr">onResume</span></span></span><br></pre></td></tr></table></figure>
<p>如日志所示，观察者没有接收到“onStop”，这肯定是被调用的，因为“ActiveGapActivity onStop调用”被打印出来了。这种行为是由两个LiveData礼:</p>
<ul>
<li>LiveData可以缓冲一个数据实例;</li>
<li>LiveData在其生命周期中不会通知观察者，而cleowner则处于“非活动”状态。</li>
</ul>
<p>当我们旋转屏幕时，活动将被重新创建。将顺序调用当前活动实例的onStop()和onDestroy()。但是，由于活动不再活动，发出的数据将不会传递给观察者。而是在内部缓冲最新的数据实例，即“onDestroy”。当活动被重新创建时，第二个活动实例将发出“onCreate”，并覆盖之前的缓冲数据“onDestroy”。一旦活动(即LifecycleOwner)恢复活动，观察者将只接收缓冲的“onCreate”。onStop和onDestroy都丢失了。<br>下图显示了在第二个活动的onCreate()中调用LiveData的setValue函数时的调试信息。显然，新的数据实例“onCreate”覆盖了先前由第一个实例的onDestroy()发出的缓冲数据实例(“mData”)。</p>
<p><img src="https://miro.medium.com/max/1077/1*OobWCz4qZm6XNHk-PxWP0A.png" alt="图片"></p>
<h2 id="从后台线程发出数据"><a href="#从后台线程发出数据" class="headerlink" title="从后台线程发出数据"></a>从后台线程发出数据</h2><p>LiveData在主线程上调度数据。如果源从后台线程发出数据，则下游使用者不会立即收到更新。相反，发出的数据将在LiveData中进行缓冲，并等待主线程稍后进行调度。但是，由于LiveData只缓冲一个数据实例，如果数据源发出的数据比主线程分派的数据“更快”。新数据实例可能会覆盖已缓存的数据实例，从而导致数据丢失。<br>让我们来看看下面的例子。在onResume()中启动一个AsyncTask，并向LiveData发送三个数据实例;在“onCreate”中初始化输出数据的观察者。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PostValueSampleActivity</span> <span class="title">extends</span> <span class="title">BaseActivity</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MutableLiveData&lt;Integer&gt; source;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> void onCreate(Bundle savedInstanceState) &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line"></span><br><span class="line">        source = new MutableLiveData&lt;&gt;();</span><br><span class="line">        source.observe(<span class="keyword">this</span>, new Observer&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> void onChanged(<span class="meta">@Nullable</span> Integer integer) &#123;</span><br><span class="line">                append(integer.toString());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> void onResume() &#123;</span><br><span class="line">        <span class="keyword">super</span>.onResume();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        AsyncTask.execute(new Runnable() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> void run() &#123;</span><br><span class="line">                source.postValue(<span class="number">1</span>);</span><br><span class="line">                source.postValue(<span class="number">2</span>);</span><br><span class="line">                source.postValue(<span class="number">3</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>示例代码将只输出“3”，这是AsyncTask发出的最后一个数据。这个输出背后的魔力可以在LiveData的源代码中找到。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> void postValue(T value) &#123;</span><br><span class="line">      boolean postTask;</span><br><span class="line">      synchronized (mDataLock) &#123;</span><br><span class="line">          postTask = mPendingData == NOT_SET;</span><br><span class="line">          mPendingData = value;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (!postTask) &#123;</span><br><span class="line">          <span class="keyword">return</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>当一个后台线程向LiveData发送数据时，LiveData会将一个标记、postTask标记为true;发布一个runnable到主线程，将数据更改发送给观察者。如果后台线程发出数据“太频繁”(在主线程可运行完成之前)，新发布的数据将覆盖“mPendingData”。当主thead执行runnable并尝试分发数据更改时，它将获得最后的数据，即“mPendingData”保存的数据。</p>
<h2 id="在观察者中发射数据"><a href="#在观察者中发射数据" class="headerlink" title="在观察者中发射数据"></a>在观察者中发射数据</h2><p>由于LiveData在主线程上调度数据，所以在调度已经启动时，所有的事情都是(某种程度上)同步的。所有观察者将被迭代，并依次接收更新。但是，如果在观察者内部设置新的数据更改，则新的数据更改(我们称之为“B”)将覆盖当前正在调度的数据更改(我们称之为“A”)并终止当前调度周期。一些观察者可能不会永远得到“A”。<br>假设有两个观察者。观察者2打印接收到的内容，但是如果接收到的数字是偶数，观察者1将把新值设置回LiveData。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SetValueSampleActivity</span> <span class="title">extends</span> <span class="title">BaseActivity</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MutableLiveData&lt;Integer&gt; source;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> void onCreate(Bundle savedInstanceState) &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line"></span><br><span class="line">        source = new MutableLiveData&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        source.observe(<span class="keyword">this</span>, new Observer&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> void onChanged(<span class="meta">@Nullable</span> Integer integer) &#123;</span><br><span class="line">                append(<span class="string">"Receiver 1: "</span> + integer.toString());</span><br><span class="line">                <span class="keyword">if</span> (integer % <span class="number">2</span> == <span class="number">0</span>) &#123;</span><br><span class="line">                    source.setValue(integer * <span class="number">10</span>);</span><br><span class="line">                    source.setValue(integer * <span class="number">10</span> + <span class="number">1</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        source.observe(<span class="keyword">this</span>, new Observer&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> void onChanged(<span class="meta">@Nullable</span> Integer integer) &#123;</span><br><span class="line">                append(<span class="string">"Receiver 2: "</span> + integer.toString());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> void onResume() &#123;</span><br><span class="line">        <span class="keyword">super</span>.onResume();</span><br><span class="line"></span><br><span class="line">        source.setValue(<span class="number">1</span>);</span><br><span class="line">        source.setValue(<span class="number">2</span>);</span><br><span class="line">        source.setValue(<span class="number">3</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此示例的输出如下图所示。观察者1收到1 2 21 3，观察者2收到1 21 3。</p>
<p><img src="https://miro.medium.com/max/1078/1*QLCjpBsQ_DezOpQIEbI4PQ.png" alt="图片"></p>
<p>这种行为背后的原因有点复杂。让我们检查LiveData中的“dispatchingValue()”函数。从第2行到第6行可以看出，如果调度已经启动，任何新的数据集都不会启动另一个调度循环。相反，新的数据更改将覆盖挂起的数据(在setValue()函数中)，将“mDispatchInvalidated”设置为true并跳过(从第2行到第5行)。在我们的示例中，当观察者1接收到“2”时，它将“20”和“21”设置回LiveData。因为“mDispatchingValue”为真，所以“20”将不会被分派，而是被“21”覆盖。观察者1的逻辑完成后，由于“mDispatchInvalidated”为真，它将中断当前调度循环(从第13行到第19行，并停止观察者2接收“2”)，并使外部while循环再运行一次(从第7行到第21行)。在这个调度循环中，所有的观察者接收最后的数据“21”。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> void dispatchingValue(<span class="meta">@Nullable</span> ObserverWrapper initiator) &#123;</span><br><span class="line">       <span class="keyword">if</span> (mDispatchingValue) &#123;</span><br><span class="line">           mDispatchInvalidated = <span class="literal">true</span>;</span><br><span class="line">           <span class="keyword">return</span>;</span><br><span class="line">       &#125;</span><br><span class="line">       mDispatchingValue = <span class="literal">true</span>;</span><br><span class="line">       <span class="keyword">do</span> &#123;</span><br><span class="line">           mDispatchInvalidated = <span class="literal">false</span>;</span><br><span class="line">           <span class="keyword">if</span> (initiator != <span class="literal">null</span>) &#123;</span><br><span class="line">               considerNotify(initiator);</span><br><span class="line">               initiator = <span class="literal">null</span>;</span><br><span class="line">           &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">               <span class="keyword">for</span> (Iterator&lt;Map.Entry&lt;Observer&lt;T&gt;, ObserverWrapper&gt;&gt; iterator =</span><br><span class="line">                       mObservers.iteratorWithAdditions(); iterator.hasNext(); ) &#123;</span><br><span class="line">                   considerNotify(iterator.next().getValue());</span><br><span class="line">                   <span class="keyword">if</span> (mDispatchInvalidated) &#123;</span><br><span class="line">                       <span class="keyword">break</span>;</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">while</span> (mDispatchInvalidated);</span><br><span class="line">       mDispatchingValue = <span class="literal">false</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>github code↓↓<br><a href="https://github.com/hanyuliu/livedata_may_lose_data" target="_blank" rel="noopener">https://github.com/hanyuliu/livedata_may_lose_data</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>============ END ============</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="段燚涛 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="段燚涛 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Jetpack/" rel="tag"># Jetpack</a>
          
            <a href="/tags/LiveData/" rel="tag"># LiveData</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/06/22/HTML-基础/" rel="next" title="HTML 基础">
                <i class="fa fa-chevron-left"></i> HTML 基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/03/11/使用-Chronometer-实现倒计时/" rel="prev" title="使用 Chronometer 实现倒计时">
                使用 Chronometer 实现倒计时 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MzUzNC8yMDA3Mw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpeg" alt="段燚涛">
            
              <p class="site-author-name" itemprop="name">段燚涛</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">17</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/duanyitao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:duanyitao7937@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                快速链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/googlesamples/android-architecture/tree/todo-mvvm-databinding/todoapp" title="Android-architecture" target="_blank">Android-architecture</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://developer.android.google.cn/jetpack" title="Jetpack" target="_blank">Jetpack</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#将数据发送到活动状态之外"><span class="nav-number">1.</span> <span class="nav-text">将数据发送到活动状态之外</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#从后台线程发出数据"><span class="nav-number">2.</span> <span class="nav-text">从后台线程发出数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#在观察者中发射数据"><span class="nav-number">3.</span> <span class="nav-text">在观察者中发射数据</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Build by duanyitao.</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">38.6k</span>
  
</div>









        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


</body>
</html>
